from django import forms
from django import template
from skoolmaster.general import widgets

register = template.Library()

class HorizFilterForm(forms.Form):
  """
  A form containing a multi-select field with the horizontal filter widget.
  """
  def __init__(self, id, name, choices = None, initial = None, *args, **kwargs):
    super(HorizFilterForm, self).__init__(*args, **kwargs)
    
    self.fields[id] = forms.MultipleChoiceField(
      initial = initial, 
      choices = choices,
      widget = widgets.HorizontalFilterWidget(name)
    )
    self.fields[id].label = ''

def id_gen():
  """
  Generate unique IDs for the filters
  """
  i = 0
  while True:
    yield i
    i = i + 1 
    
FILTER_ID = id_gen()

@register.inclusion_tag('general/horiz_filter.html')
def horiz_filter(name, selected, all):
  """
  Renders a fancy JavaScript horizontal filter.
  """
  form = HorizFilterForm(
    str(FILTER_ID.next()), 
    name, 
    choices = [(item.pk, str(item)) for item in all], 
    initial = [item.pk for item in selected]
  )
  return {'form' : form }
